﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Se.Common
{
    /// <summary>
    /// 通用类
    /// </summary>
    public static class Utility
    {
        /// <summary>
        /// 生成唯一Id(long)
        /// </summary>
        /// <returns></returns>
        public static long GenerateLongId()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            long id = BitConverter.ToInt64(buffer, 0);
            return id;
        }

        /// <summary>
        /// 生成唯一Id
        /// </summary>
        /// <returns></returns>
        public static string GenerateStringId()
        {
            // 36位字符创
            string id = Guid.NewGuid().ToString();
            return id;
        }

        /// <summary>
        /// 获取当前的程序集集合
        /// </summary>
        /// <returns></returns>
        public static List<Assembly> GetCurrentAssemblies()
        {
            List<Assembly> list = new List<Assembly>();
            Assembly entryAssembly = Assembly.GetEntryAssembly();
            if (entryAssembly != null)
            {
                AssemblyName[] referencedAssemblies = entryAssembly.GetReferencedAssemblies();
                list.Add(entryAssembly);
                foreach (AssemblyName name in referencedAssemblies)
                {
                    Assembly item = Assembly.Load(name);
                    if (!((item == null) || item.GlobalAssemblyCache))
                    {
                        list.Add(item);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 转换成随机的List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="inputList"></param>
        /// <returns></returns>
        public static List<T> GetRandomList<T>(List<T> inputList)
        {
            //Copy to a array
            T[] copyArray = new T[inputList.Count];
            inputList.CopyTo(copyArray);

            //Add range
            List<T> copyList = new List<T>();
            copyList.AddRange(copyArray);

            //Set outputList and random
            List<T> outputList = new List<T>();
            Random rd = new Random(DateTime.Now.Millisecond);

            while (copyList.Count > 0)
            {
                //Select an index and item
                int rdIndex = rd.Next(0, copyList.Count - 1);
                T remove = copyList[rdIndex];

                //remove it from copyList and add it to output
                copyList.Remove(remove);
                outputList.Add(remove);
            }
            return outputList;
        }
    }
}
